package com.example.huangliting.experimentalarrangementsystem.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.huangliting.experimentalarrangementsystem.MyScheduleView;
import com.example.huangliting.experimentalarrangementsystem.R;
import com.example.huangliting.experimentalarrangementsystem.ScheduleView;
import com.example.huangliting.experimentalarrangementsystem.bean.BoxMsg;
import com.example.huangliting.experimentalarrangementsystem.bean.ClassInfo;
import com.example.huangliting.experimentalarrangementsystem.util.DateUitls;
import com.example.huangliting.experimentalarrangementsystem.util.HttpUtils;
import com.example.huangliting.experimentalarrangementsystem.util.Utils;
import com.example.huangliting.experimentalarrangementsystem.view.KBCalendar;
import com.example.huangliting.experimentalarrangementsystem.view.TwoWayView;
import com.zaaach.toprightmenu.MenuItem;
import com.zaaach.toprightmenu.TopRightMenu;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyScheduleViewAct extends AppCompatActivity {

    private final String getMyClassUrl = HttpUtils.headerUrl+"timetable/getPersonClassAWeek";
    private final String updateMyClassUrl = HttpUtils.headerUrl+"timetable/updateMyClass";
    private Context mcontext;
    private MyScheduleView myScheduleView;
    private TwoWayView twoWayView;
    private ArrayList<ClassInfo> classList;
    private ArrayList<ClassInfo> tempClassList;
    private ArrayList<ClassInfo> dealClassList;
    private List<String> dateStrX;
    private TextView mDataSelect;
    private TextView mDataScroll;
    private TextView title_tv;
    private TextView title_tv_small;
    private LinearLayout titleLinearLayout;
    private String selectDate = null;
    private SharedPreferences sp;
    private Button settingBtn;
    private Button backBtn;
    private int thisWeekNum;
    private String  semesterStr;
    private ArrayList<Date> mListDays;
    private String weekid;
    //private String[] nameX;

    public static final int SHOW_RESPONSE = 0;

    JSONArray timetable = null;
    JSONArray nameX = null;
    JSONObject titleJson = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_schedule_view);
        mcontext = this;
        myScheduleView = (MyScheduleView) findViewById(R.id.myScheduleView);
        title_tv = findViewById(R.id.toolbar_title_tv);
        title_tv_small = findViewById(R.id.toolbar_title_tv_small);
        titleLinearLayout = (LinearLayout) findViewById(R.id.title_LinearLayout);

        sp = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        //获取当周我的课程
        Map<String, String> params = new HashMap<String, String>();
        params.put("tid",sp.getString("userId",""));
        getDataByPost(params, "utf-8");

        myScheduleView.setOnItemClassClickListener(new ScheduleView.OnItemClassClickListener() {
            @Override
            public void onClick(ClassInfo classInfo) {
                String[] items = new String[classInfo.getClassidList().size()];
                for (int i = 0; i < classInfo.getClassidList().size(); i++){
                    items[i] = classInfo.getClassidList().get(i).getClassname();
                }
                showListAlertDialog(items,classInfo.getClassidList());
            }
        });

        /*myScheduleView.setOnNoItemClassClickListener(new ScheduleView.OnItemNoClassClickListener() {
            @Override
            public void onClick(BoxMsg boxMsg) {

                Intent i = new Intent(mcontext, AddLessonActivity.class);
                Bundle b = new Bundle();
                b.putInt("nextclassNum", boxMsg.getNextclassNum());
                b.putInt("xnum", boxMsg.getxNum());
                b.putInt("ynum", boxMsg.getyNum());
                b.putString("classAddr",nameStrX.get(boxMsg.getxNum()-1));
                b.putString("classDate", String.valueOf(selectDate));
                try {
                    b.putString("weekid", titleJson.getString("weekid"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                i.putExtras(b);
                startActivityForResult(i, 1);

            }
        });*/

        settingBtn = findViewById(R.id.toolbar_right_btn);
        settingBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(mcontext, SetWeekActivity.class);
                Bundle b = new Bundle();
                b.putInt("thisWeekNum", thisWeekNum);
                b.putString("semester", semesterStr);
                i.putExtras(b);
                startActivityForResult(i,2);
            }
        });

        /*返回操作*/
        backBtn = findViewById(R.id.toolbar_left_btn);
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                finish();
            }
        });

    }

    private void getClassData() {
        classList = new ArrayList<ClassInfo>();
        ClassInfo classInfo = new ClassInfo();
        classInfo.setClassname("数据库原理与");
        classInfo.setFromClassNum(3);
        classInfo.setClassNumLen(2);
        classInfo.setClassRoom("C1-403");
        classInfo.setxNum(1);
        classList.add(classInfo);

        ClassInfo classInfo1 = new ClassInfo();
        classInfo1.setClassname("人机交互");
        classInfo1.setFromClassNum(3);
        classInfo1.setClassNumLen(2);
        classInfo1.setClassRoom("信息机房");
        classInfo1.setxNum(1);
        classList.add(classInfo1);

        ClassInfo classInfo2 = new ClassInfo();
        classInfo2.setClassname("物联网技术及应用");
        classInfo2.setFromClassNum(3);
        classInfo2.setClassNumLen(2);
        classInfo2.setClassRoom("C1-101");
        classInfo2.setxNum(3);
        classList.add(classInfo2);

        ClassInfo classInfo3 = new ClassInfo();
        classInfo3.setClassname("应用集成原理与工具");
        classInfo3.setFromClassNum(7);
        classInfo3.setClassNumLen(2);
        classInfo3.setClassRoom("C1-205");
        classInfo3.setxNum(3);
        classList.add(classInfo3);

        ClassInfo classInfo4 = new ClassInfo();
        classInfo4.setClassname("linux系统");
        classInfo4.setFromClassNum(3);
        classInfo4.setClassNumLen(2);
        classInfo4.setClassRoom("C1-205");
        classInfo4.setxNum(5);
        classList.add(classInfo4);

        ClassInfo classInfo9 = new ClassInfo();
        classInfo9.setClassname("linux系统111");
        classInfo9.setFromClassNum(3);
        classInfo9.setClassNumLen(2);
        classInfo9.setClassRoom("C1-205sdd");
        classInfo9.setxNum(5);
        classList.add(classInfo9);

        ClassInfo classInfo5 = new ClassInfo();
        classInfo5.setClassname("ccccc");
        classInfo5.setFromClassNum(3);
        classInfo5.setClassNumLen(2);
        classInfo5.setClassRoom("aaaaa");
        classInfo5.setxNum(1);
        classList.add(classInfo5);

        ClassInfo classInfo6 = new ClassInfo();
        classInfo6.setClassname("safgg");
        classInfo6.setFromClassNum(3);
        classInfo6.setClassNumLen(2);
        classInfo6.setClassRoom("sdsdd");
        classInfo6.setxNum(1);
        classList.add(classInfo6);

        ClassInfo classInfo7 = new ClassInfo();
        classInfo7.setClassname("ajbdsfdfasdssddd");
        classInfo7.setFromClassNum(3);
        classInfo7.setClassNumLen(2);
        classInfo7.setClassRoom("uuuu");
        classInfo7.setxNum(1);
        classList.add(classInfo7);

        ClassInfo classInfo8 = new ClassInfo();
        classInfo8.setClassname("sdsahdbbbs");
        classInfo8.setFromClassNum(3);
        classInfo8.setClassNumLen(2);
        classInfo8.setClassRoom("oooooo");
        classInfo8.setxNum(1);
        classList.add(classInfo8);
    }

    //获取当周我的课程Json解析
    Handler myClassHandler = new Handler() {

        @SuppressLint("WrongConstant")
        public void handleMessage(android.os.Message msg) {
            try {
                JSONObject jsonObj = new JSONObject((String) msg.obj);
                //标题数据
                titleJson = jsonObj.getJSONObject("thisWeek");
                if (titleJson!=null){
                    //更新标题
                    title_tv_small.setText(titleJson.getString("semester"));
                    title_tv.setText("第"+titleJson.getString("weekNum")+"周");
                    thisWeekNum = titleJson.getInt("weekNum");
                    semesterStr = titleJson.getString("semester");
                    weekid = titleJson.getString("weekid");
                    //获取日期顶部栏
                    mListDays = new ArrayList<Date>();
                    String formatDate = "yyyy-MM-dd";
                    SimpleDateFormat dateFormat = new SimpleDateFormat(formatDate);
                    Date dateStartCalendar = null;
                    Date dateEndCalendar = null;
                    SimpleDateFormat sf = new SimpleDateFormat("MM月dd日");

                    try {
                        dateStartCalendar = dateFormat.parse(titleJson.getString("weekStartDate"));
                        dateEndCalendar = dateFormat.parse(titleJson.getString("weekEndDate"));
                        GregorianCalendar calendar = new GregorianCalendar();

                        calendar.setTime(dateStartCalendar);
                        Date dateStartBefore = calendar.getTime();
                        calendar.setTime(dateEndCalendar);
                        int day = calendar.get(Calendar.DATE);
                        calendar.set(Calendar.DATE, day + 1);
                        Date dateEndAfter = calendar.getTime();
                        dateStrX = new ArrayList<>();

                        for (Date date = dateStartBefore; !date.equals(dateEndAfter); ) {
                            calendar.setTime(date);
                            mListDays.add(date);
                            String dateStr = sf.format(date);
                            dateStrX.add(dateStr);
                            calendar.add(Calendar.DATE, 1);
                            date = calendar.getTime();
                        }
                        myScheduleView.setDateX(dateStrX);

                    } catch (ParseException e1) {
                        e1.printStackTrace();
                    }
                }

                //课表数据
                timetable = jsonObj.getJSONArray("timetables");
                if (timetable!=null){
                    classList = new ArrayList<ClassInfo>();
                    for (int i = 0; i < timetable.length(); i++) {
                        ClassInfo classInfo = new ClassInfo();
                        JSONObject jsonObject = timetable.getJSONObject(i);
                        classInfo.setClassid(jsonObject.getInt("cid"));
                        classInfo.setClassname(jsonObject.getString("lessonName"));
                        classInfo.setFromClassNum(jsonObject.getInt("classNum"));
                        classInfo.setClassNumLen(jsonObject.getInt("classLength"));
                        classInfo.setClassRoom(jsonObject.getString("lname"));
                        classInfo.setWeekday(jsonObject.getInt("weekday"));
                        classInfo.setBatchNum(jsonObject.getInt("batchNum"));
                        classInfo.setTeacherName(jsonObject.getString("tname"));
                        classInfo.setDbDivision(1); //为课程表中的课程
                        classList.add(classInfo);
                    }
                    tempClassList = new ArrayList<ClassInfo>();
                    tempClassList.addAll(classList);
                    dealClassListToView();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    //整理课程显示
    private void dealClassListToView() {
        dealClassList = new ArrayList<>();
        if (classList!=null){

            while (classList.size()!=0){
                List<ClassInfo> removeClassList = new ArrayList<>();
                //记录同时间段的课程
                List<ClassInfo> clist = new ArrayList<>();
                //遍历第一个是否与其他的相同

                //先将第一个课程名组织好
                classList.get(0).setClassname(classList.get(0).getClassname()+"@"+classList.get(0).getClassRoom());
                ClassInfo classInfo = new ClassInfo();
                classInfo.setClassid(classList.get(0).getClassid());
                classInfo.setClassname(classList.get(0).getClassname());
                classInfo.setClassidList(classList.get(0).getClassidList());
                classInfo.setBatchNum(classList.get(0).getBatchNum());
                classInfo.setDbDivision(classList.get(0).getDbDivision());
                classInfo.setWeekday(classList.get(0).getWeekday());
                classInfo.setClassRoom(classList.get(0).getClassRoom());
                classInfo.setTeacherName(classList.get(0).getTeacherName());
                classInfo.setFromClassNum(classList.get(0).getFromClassNum());
                classInfo.setClassNumLen(classList.get(0).getClassNumLen());

                clist.add(classList.get(0));
                removeClassList.add(classList.get(0));

                for (int i = 1; i < classList.size(); i++){
                    if (classList.get(i).getWeekday() == classInfo.getWeekday() && classList.get(i).getFromClassNum() == classInfo.getFromClassNum()){
                        classList.get(i).setClassname(classList.get(i).getClassname()+"@"+classList.get(i).getClassRoom());
                        clist.add(classList.get(i));
                        classInfo.setClassname(classInfo.getClassname()+"\n"+"+"+classList.get(i).getClassname());
                        removeClassList.add(classList.get(i));
                    }
                }
                classInfo.setClassidList(clist);
                dealClassList.add(classInfo);
                classList.removeAll(removeClassList);
            }
        }

        myScheduleView.setClassList(dealClassList);
    }

    //当周我的课程请求
    private void getDataByPost(final Map<String, String> params, final String encode) {
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    URL url = new URL(getMyClassUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);

                    //拼接出要提交的数据的字符串
                    byte[] data = HttpUtils.getRequestData(params, encode).toString().getBytes();

                    //添加post请求的两行属性
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestProperty("Content-Length", String.valueOf(data.length));

                    //设置打开输出流
                    conn.setDoOutput(true);
                    //拿到输出流
                    OutputStream os = conn.getOutputStream();
                    //使用输出流往服务器提交数据
                    os.write(data);
                    if (conn.getResponseCode() == 200) {
                        InputStream is = conn.getInputStream();
                        String text = Utils.getTextFromStream(is);
                        Message msg = myClassHandler.obtainMessage();
                        msg.obj = text;
                        myClassHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }

    // 信息列表提示框
    private AlertDialog alertDialog;
    public void showListAlertDialog(final String[] items, final List<ClassInfo> classidList){
        //final String[] items = {"Struts2","Spring","Hibernate","Mybatis","Spring MVC"};
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setTitle("课程");
        alertBuilder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int index) {
                //Toast.makeText(mcontext, items[index], Toast.LENGTH_SHORT).show();
                Intent i = new Intent(mcontext, MyScheduleDetailAct.class);
                Bundle b = new Bundle();
                b.putInt("cid", classidList.get(index).getClassid());
                b.putInt("dbDivision",classidList.get(index).getDbDivision());
                i.putExtras(b);
                startActivityForResult(i,1);
                alertDialog.dismiss();
            }
        });
        alertDialog = alertBuilder.create();
        alertDialog.show();
    }

    private void updateDateAndTitleByPost(final Map<String, String> params, final String encode) {
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    URL url = new URL(updateMyClassUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);

                    //拼接出要提交的数据的字符串
                    byte[] data = HttpUtils.getRequestData(params, encode).toString().getBytes();

                    //添加post请求的两行属性
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestProperty("Content-Length", String.valueOf(data.length));

                    //设置打开输出流
                    conn.setDoOutput(true);
                    //拿到输出流
                    OutputStream os = conn.getOutputStream();
                    //使用输出流往服务器提交数据
                    os.write(data);
                    if (conn.getResponseCode() == 200) {
                        InputStream is = conn.getInputStream();
                        String text = Utils.getTextFromStream(is);
                        Message msg = myClassHandler.obtainMessage();
                        msg.obj = text;
                        myClassHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }


    /**
     * 此方法用来跳转的activity要传回的数据，以及接受到传回数据的要做的业务
     * 这里因为只有一个activity返回数据，所以这里就只有一个resultCode，就直接接收返回值处理
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (1 == requestCode) {
            /*Map<String, String> params = new HashMap<String, String>();
            params.put("tid",sp.getString("userId",""));
            getDataByPost(params,"utf-8");*/
            Map<String, String> params = new HashMap<String, String>();
            params.put("tid",sp.getString("userId",""));
            params.put("weekid",weekid);
            updateDateAndTitleByPost(params, "utf-8");
        }

        if (2 == requestCode) {
            Bundle bundle = data.getExtras();
            Map<String, String> params = new HashMap<String, String>();
            params.put("tid",sp.getString("userId",""));
            weekid = bundle.getString("weekid");
            params.put("weekid",weekid);
            updateDateAndTitleByPost(params, "utf-8");
        }
    }
}
